import { filterObj } from '@/utils/util';
import { deleteAction, getAction,downFile } from '@/api/manage'
import Vue from 'vue'
import { ACCESS_TOKEN } from "@/store/mutation-types"
import Pagination from '@/components/Pagination'


export const SingleTableMixins = {
  components:{Pagination},
  data(){
    return {
      //token header
      tokenHeader: {'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)},
      searchModel:{},
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /* 数据源 */
      dataSource:[],
      /* 分页参数 */
      ipagination:{
        pageSize: 10,
        current:1,
        total: 0,
      },
      /* 排序参数 */
      isorter:{
        column: 'createTime',
        order: 'desc',
      },
      url:{},
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading:false,
      /* 查询折叠 */
      toggleSearchStatus:false,
      /* 高级查询条件生效状态 */
      superQueryFlag:false,
      /* 高级查询条件 */
      superQueryParams:"",
      singleSelRows:{},
      singleSelRowKey :'',
      disableMixinCreated:false
    }
  },
  created() {
    if (!this.disableMixinCreated) {
        console.log(' -- mixin created -- ')
        this.loadData();
        //初始化字典配置 在自己页面定义
        this.initDictConfig();
    }
  },
  watch:{
    singleSelRows(val){
      this.selectChange(val);
    }
  },
  methods:{
    loadData(arg) {
      let that = this;
      if(!this.url.list){
        this.$message.error("请设置url.list属性!")
        return
      }

      if(arg === 1){
        this.ipagination.current = 1;
      }
      //加载数据 若传入参数1则加载第一页的内容
      var params = this.getQueryParams();//查询条件
      that.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          if( res.data.records){
            that.dataSource = res.data.records;
            that.ipagination.total = res.data.total;
          }else{
            that.dataSource = res.data;
          }
          that.singleSelRowKey = "";
          that.singleSelRows = {};
          that.selectChange();
        }
        if(res.code===510){
          this.$message.warning(res.messag)
        }
        that.loading = false;
      })
    },
    searchQuery() {
      this.loadData(1);
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if(this.superQueryParams){
        sqp['superQueryParams']=encodeURI(this.superQueryParams)
      }
      var param = Object.assign({},this.queryParam, this.searchModel, this.isorter ,this.filters);
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      return filterObj(param);
    },
    searchReset() {
      this.searchModel = {}
      this.loadData(1);
    },
    getQueryField() {
      //TODO 字段权限控制
      // var str = "id,";
      // this.columns.forEach(function (value) {
      //   str += "," + value.dataIndex;
      // });
      return "";
    },
    initDictConfig(){

    },
    handleAdd: function () {
      this.$refs.modalForm.add();
      this.$refs.modalForm.title = "新增";
      this.$refs.modalForm.disableSubmit = false;
    },
    handleEdit: function (record) {
      this.$refs.modalForm.edit(record);
      this.$refs.modalForm.title = "编辑";
      this.$refs.modalForm.disableSubmit = false;
    },
    handleDelete: function (id) {
      if(!this.url.delete){
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      deleteAction(that.url.delete, {id: id}).then((res) => {
        if (res.success) {
          this.$message.success(res.message );
          that.loadData();
        } else {
          this.$message.warning(res.message )
        }
      });
    },
    handleToggleSearch(){
      this.toggleSearchStatus = !this.toggleSearchStatus;
    },
    handleDetail:function(record){
      this.$refs.modalForm.edit(record);
      this.$refs.modalForm.title="查看";
      this.$refs.modalForm.disableSubmit = true;
    },
    modalFormOk() {
      // 新增/修改 成功时，重载列表
      this.loadData();
    },
    rowClick(row, column, event){
      this.singleSelRowKey = row.id;
      this.singleSelRows = row;
    },
    selectChange:()=>{},
    handleExportXls(fileName){
      if(!fileName || typeof fileName != "string"){
        fileName = "导出文件"
      }
      let param = {...this.getQueryParams()};
      console.log("导出参数",param)
      downFile(this.url.exportXlsUrl,param).then((data)=>{
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), fileName+'.xls')
        }else{
          let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName+'.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    },
    /* 导入 */
    handleImportExcel(info){
      console.log(info);
      if (info.status !== 'uploading') {
        console.log(info);
      }
      if (info.status === "success") {
        if (info.response.success) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.response.code === 201) {
            let { message, result: { msg, fileUrl, fileName } } = info.response
            let href = window._CONFIG['domianURL'] + fileUrl
            this.$message.warning({
                title: message,
                content: (
                      <div>
                        <span>{msg}</span><br/>
                        <span>具体详情请 <a href={href} target="_blank" download={fileName}>点击下载</a> </span>
                      </div> )
                 })
          } else {
            this.$message.success(info.response.message || `${info.name} 文件上传成功`)
          }
          this.loadData()
        } else {
          this.$message.error(`${info.name} ${info.response.message}.`);
        }
      } else if (info.status === 'error') {
        this.$message.error(`文件上传失败: ${info.msg} `);
      }
    },
  }
}
